﻿using Newtonsoft.Json;
using StackExchange.Redis;
namespace CommandLib
{
    /// <summary>
    /// Redis管理
    /// </summary>
    public static class RedisManager
    {
        private static ConfigurationOptions configurationOptions;
        private static ConnectionMultiplexer connectionMultiplexer;
        private static IDatabase database;
        public static IDatabase RedisBase { get { return database; } }

        /// <summary>
        /// REDIS注册
        /// </summary>
        /// <param name="connections">连接串</param>
        public static void Init(string connections)
        {
            try
            {
                configurationOptions = ConfigurationOptions.Parse(connections);
                connectionMultiplexer = ConnectionMultiplexer.Connect(configurationOptions);
                if (connectionMultiplexer != null)
                {
                    database = connectionMultiplexer.GetDatabase();
                }

            }
            catch (Exception)
            {
                throw;
            }

        }

        /// <summary>
        /// 获取键
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>

        public static string Get(string key)
        {

            return database.StringGet(key);
        }
        /// <summary>
        /// 设置主键
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetKey(string key, string value, TimeSpan? timeSpan=null)
        {
            if (timeSpan.HasValue)
            {
                database.StringSet(key, value, timeSpan);
            }
            else
            {
                database.StringSet(key, value);
            }

        }
        /// <summary>
        /// 获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetObject<T>(string key)
        {
            var result = default(T);
            var json = database.StringGet(key);
            if (!json.HasValue)
            {
                var settings = new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore,
                };
                settings.ContractResolver = new LongNameContractResolver();
                result = JsonConvert.DeserializeObject<T>(json.ToString(), settings);
            }
            return result;
        }
        /// <summary>
        /// 删除KEY
        /// </summary>
        /// <param name="key"></param>
        public static void Delete(string key) {

            database.StringGetDelete(key);        
        }
        /// <summary>
        ///  订阅
        /// </summary>
        /// <param name="subChannel">渠道</param>
        /// <param name="action">接收消息</param>
        public static void RedisSub(string subChannel, Action<string> action)
        {
            connectionMultiplexer
                .GetSubscriber()
                .Subscribe(subChannel, (channel, message) =>
                {

                    if (action != null)
                    {
                        action(message);
                    }

                });

        }

        /// <summary>
        ///  消息发部
        /// </summary>
        /// <param name="channel">渠道</param>
        /// <param name="msg">消息</param>
        /// <returns></returns>
        public static long RedisPub(string channel, object msg)
        {
            var settings = new JsonSerializerSettings
            {
                DefaultValueHandling = DefaultValueHandling.Ignore,
            };
            settings.ContractResolver = new LongNameContractResolver();
            return connectionMultiplexer
                .GetSubscriber()
                .Publish(channel, JsonConvert.SerializeObject(msg, settings));
        }

    }
}
